package cn.com.longfuinfo.wx.controller;


import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;

import com.jfinal.aop.Clear;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.weixin.sdk.api.ApiConfigKit;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.api.SnsAccessToken;
import com.jfinal.weixin.sdk.api.SnsAccessTokenApi;
import com.jfinal.weixin.sdk.api.SnsApi;

import cn.com.longfuinfo.wx.common.Constants;
import cn.com.longfuinfo.wx.dao.User;
import cn.com.longfuinfo.wx.dao.WxUser;
import cn.com.longfuinfo.wx.dao.AdSeller;
import cn.com.longfuinfo.wx.dao.HomeBag;
import cn.com.longfuinfo.wx.kit.CommonKit;
import cn.com.longfuinfo.wx.kit.DatetimeKit;
import cn.com.longfuinfo.wx.kit.SMSKit;
import cn.com.longfuinfo.wx.kit.ValidateKit;
import cn.com.longfuinfo.wx.service.GoodsService;
import cn.com.longfuinfo.wx.service.StoreService;
import cn.com.longfuinfo.wx.service.UserService;

public class SystemController extends BaseController {
	private Logger logger = Logger.getLogger(getClass());
	private StoreService storeService = new StoreService();
	private UserService userService = new UserService();
	private GoodsService goodservice = new GoodsService();

	/**
	 * 跳转首页
	 */
	public void index() {
		 WxUser wxuser=getCurrentWxUser();		
		//测试
		// WxUser user=WxUser.me().findById(142);
		 //setSessionAttr(Constants.WX_USER, user);
		 
		if(wxuser==null){
			/*redirect("/index");*/
			render("index.jsp");
			logger.error("微信用户为null");

		}else{
			//设置导购id到Session
			if ( wxuser.getStr("daogouUid")!=null &&  wxuser.getStr("daogouUid")!="") {
				setSessionAttr("inviteUserid", wxuser.getStr("daogouUid"));
			}else {
				logger.error("导购id为null或不是第一次扫码登陆");
			}
			
			int userid=wxuser.getInt("userid");
			if(userid !=0){
				if(getSessionAttr("cityId")!=null && !getSessionAttr("cityId").equals(0)){
					int cityId=getSessionAttr("cityId");
					Record record=storeService.getCity(cityId);
					setAttr("cityId", cityId);
					setAttr("cityName", record.get("name"));
				}else{
					int cityId=187;
					Record record=storeService.getCity(cityId);
					setAttr("cityId", cityId);
					setAttr("cityName", record.get("name"));
					setSessionAttr("cityId", cityId);
				}
				// 获取对应的用户信息
				User users =userService.findByUser(userid) ;
				if (users != null) {
					logger.error("关联用户存在：\n" + users);
					setSessionAttr(Constants.USER, users);
					setAttr("sppoint",users.getInt("sppoint"));
					setAttr("jkpoint",users.getInt("jkpoint"));
					setAttr("jypoint",users.getInt("jypoint"));
				} else {
					//用户不存在
					 setSessionAttr("userid", "0");
					logger.error("关联用户不存在！");
					/* redirect("/regist");*/
					render("index.jsp");
					 return ;
				}
				// 1.店铺轮播图
				setAttr("adList", storeService.findAd());
				setAttr("bestTitle", userService.findBestTitle());
				setAttr("doingList", goodservice.getHodingHomeList());
				
				/***
				 * 首页弹窗
				 */	
				
				HomeBag homeBag=getGifts(users);
				if(homeBag!=null){
					setAttr("homeBag", homeBag);
				}else{
					logger.error("homeBag首页弹窗为null\n" + users);
				}

				render("index.jsp");
			}else{
				//如果微信用户中userid等于0，则此微信用户没有绑定手机号或注册
				logger.error("此微信没有关联会员，关联用户不存在！游客浏览");
				if(getSessionAttr("cityId")!=null && !getSessionAttr("cityId").equals(0)){
					int cityId=getSessionAttr("cityId");
					Record record=storeService.getCity(cityId);
					setAttr("cityId", cityId);
					setAttr("cityName", record.get("name"));
				}else{
					int cityId=187;
					Record record=storeService.getCity(cityId);
					setAttr("cityId", cityId);
					setAttr("cityName", record.get("name"));
					setSessionAttr("cityId", cityId);
				}
				setAttr("sppoint",0);
				setAttr("jkpoint",0);
				setAttr("jypoint",0);
				
				//用户不存在
				 setSessionAttr("userid", "0");
				// 1.店铺轮播图
				setAttr("adList", storeService.findAd());
				setAttr("bestTitle", userService.findBestTitle());
				setAttr("doingList", goodservice.getHodingHomeList());
				render("index.jsp");

			}
		}
	
	}
	/***
	 * 首页弹窗礼包*  优先级： 1入门礼 2立即发送 3 定时发送 4生产礼 5生日礼
	 */
	public HomeBag getGifts(User users){
		
		if(users==null){
			return null;
		}
        
        String nowDay=DatetimeKit.getFormatDate("yyyy-MM-dd");  //当前时间字符串
        Date birthday=users.getDate("birthday");
        
        Calendar nowDate  = Calendar.getInstance();//当前时间日历
        Calendar birthDate = Calendar.getInstance();//生日日历
      
        
  //      System.out.println(DatetimeKit.getFormatDate(birthDate.getTime(),"yyyy-MM-dd")+"============"+between);
        

		//入门礼				
        HomeBag record2 =userService.findFirstWindow();
        System.out.println("novice============"+users.getInt("novice"));
		if(users.getInt("novice")!=null && users.getInt("novice")==1 && record2!=null) {
			record2.set("seeNum", record2.getInt("seeNum")+1).update();
			return record2;
		}
		
		
		List<HomeBag> sendlist=userService.findNowSend();
		if(sendlist !=null && sendlist.size()>0){ //立即发送
			for (HomeBag record : sendlist) {
				Record giftlog=userService.findGiftLog(record.getInt("id"), users.getInt("id"));
				if(giftlog==null) {
					record.set("seeNum", record.getInt("seeNum")+1).update();
					return record;
				}
			}
		}
		
		List<HomeBag> delaylist=userService.findDelaySend(nowDay);
		if(delaylist !=null && delaylist.size()>0){
			for (HomeBag record : delaylist) {   //定时发送
				Record giftlog=userService.findGiftLog(record.getInt("id"), users.getInt("id"));
				if(giftlog==null) {
					record.set("seeNum", record.getInt("seeNum")+1).update();
					return record;
				}
			}
		}
		
		//生日礼
		if(users.getInt("birthBag")!=null&&users.getInt("birthBag")==0){
			String[] giftyear=users.getStr("giftYear").split(",");
			String year=giftyear[0];
			if(!year.equals(String.valueOf(nowDate.get(Calendar.YEAR)))) users.set("birthBag", 1);//领过 但不是今年
		}
		if(users.getInt("birthBag")!=null && birthday!=null && users.getInt("birthBag")==1){
			  birthDate.setTime(birthday);
		      birthDate.set(Calendar.YEAR, nowDate.get(Calendar.YEAR));//今年生日
		      int btwBirth=nowDate.get(Calendar.DAY_OF_YEAR)-birthDate.get(Calendar.DAY_OF_YEAR);//当时时间与今年生日相差天数
		      if(-10<=btwBirth && btwBirth<=0 || btwBirth>=355){
		    	  HomeBag record= userService.findBirthdayWindow();
		    	  if (record!=null && record.getInt("seeNum")!=null) {
		    		  record.set("seeNum", record.getInt("seeNum")+1).update();
		    	  }
		    	  
		    	  return record;
		      } 
		}
		
		//生产礼
		if(users.getInt("babyBag")!=null &&users.getInt("babyBag")==1){
			 HomeBag record= userService.findProductionWindow();
	    	  record.set("seeNum", record.getInt("seeNum")+1).update();
	    	  return record;
		} 
		return null;
	}
	/**
	 * 选择城市
	 */
	public void chooseCity(){
		int cityId=getParaToInt(0,0);
		if(cityId !=0){
			Record record=storeService.getCity(cityId);
			setAttr("cityId", cityId);
			setAttr("cityName", record.get("name"));
			setAttr("cityList", storeService.findCity());
			render("city.jsp");
		}else{
			redirect("/index");
		}
	}
	public void choose(){
		int cityId=getParaToInt(0,0);
		setSessionAttr("cityId", cityId);
		redirect("/index");
	}
	/**
	 * 填写用户详细信息
	 */
	public void info() {
//		User user=getCurrentUser();
		String phone=getPara("phone");
		if(StrKit.isBlank(phone)){
			//
			logger.info("手机号为空，异常状态====info()=>");
			render("regist.jsp");
		}else{
			setAttr("phone", phone);
			logger.info("传递扫码导购ID====info()=>");
			setAttr("sid", getSessionAttr("inviteUserid"));
			setAttr("date", DatetimeKit.getFormatDate("yyyy-MM-dd"));
			setAttr("h_date", DatetimeKit.getDate(0,10,0));
			render("info.jsp");
		}
	}
	public void gonglue(){
		render("home.html");
	}
	/**
	 * 用户手机号已经存在，直接登录
	 */
	public void dologin(){
	    WxUser wxuser=getCurrentWxUser();
		String phone=getPara(0);
		User users= userService.findByPhone(phone);
		String daogou = users.getStr("daogou");
		//如果扫导购员二位码注册
		String daogouID = getSessionAttr("inviteUserid");
		
		if(daogou==null||daogou==""||daogou=="微商城-未扫码"){
			if (daogouID!=null && daogouID!="") {
				//获取导购实例
				AdSeller adSeller =  userService.findByAdSellerUid(daogouID);
				if (adSeller!=null) {
					users.set("daogou", adSeller.get("trueName"));
				}else{
					logger.info("未获得导购信息=====>-"+adSeller);
				}
			}else{
				logger.info("不是导购员扫码注册=====>-");
			}
			
			
		}else {
			logger.info("用户已经绑定导购员===不能重复绑定==>-"+daogou);
		}
		//设置用户关注状态
		users.set("guanzhu", 2).update();
		//设置微信用户表关联用户表
		wxuser.set("userid", users.getInt("id")).update();
		setSessionAttr("userid", users.getInt("id"));
		redirect("/index");
	}
	/**
	 * 用户注册
	 * 
	 * @param PHONE
	 *            手机号码
	 * @param PASSWORD
	 *            密码
	 * @param CODE
	 *            短信验证码
	 * @return 1：手机号不能为空，2：手机号格式不正确，3：手机号已经存在，不能重复注册，4：密码不能为空，5：密码只能填写数字、字母、下划线组合，
	 *         6：请保持密码长度在6-18之间，7：确认密码不能为空，8：两次密码输入不一致，9：验证码，10：未获取短信验证码，请重新获取，11：验证码不正确，12：邀请码不正确
	 * @throws Exception
	 */
	public void doRegist() throws Exception {
		String msisdn = getPara("phone");
		String code = getPara("code");
		// 验证各参数
		if (StrKit.isBlank(msisdn)) {
			renderResult(1, "手机号不能为空");
			return;
		} else if (!ValidateKit.Mobile(msisdn)) {
			renderResult(2, "手机号格式不正确");
			return;
		} else if (userService.findByPhone(msisdn) != null) {
			renderResult(3, "手机号已经存在，立即绑定");
			return;
		} else if (StrKit.isBlank(code)) {
			renderResult(7, "验证码不能为空");
			return;
		}
		// 验证短信验证码
		String codeInSession = getSessionAttr("REGIST_VALID_CODE");
		if (StrKit.isBlank(codeInSession)) {
			renderResult(8, "未获取短信验证码，请重新获取");
			return;
		} else if (!codeInSession.equals(code)) {
			renderResult(9, "验证码不正确");
			return;
		}
		// 移除缓存中的验证码
		removeSessionAttr("REGIST_VALID_CODE");
		renderSuccess();
		return;
		
	}

	/**
	 * 注册时，生成并发送N位短信验证码
	 * 
	 * @param PHONE
	 *            手机号码
	 * @return CONTENT 生成并发送的N位短信验证码
	 */
	public void sendRegCode() {
		String phone = getPara("phone");
		if (StrKit.isBlank(phone)) {
			renderResult(1, "参数PHONE不能为空");
			return;
		} 
		// 判断session中是否已经存在未过期的验证码
		String randomNum = getSessionAttr("REGIST_VALID_CODE");
		if (randomNum == null) {
			// 否则生成新的验证码
			randomNum = CommonKit.randomNum();
		}
		if (SMSKit.sendTplSms(phone, randomNum)) {
			setSessionAttr("REGIST_VALID_CODE", randomNum);
			if (PropKit.getBoolean("debug.sms")) {
				// 短信接口调试模式时，将短信验证码返回给客户端
				renderSuccess(randomNum);
				return;
			} else {
				renderSuccess();
				return;
			}
		}
		renderFailed("验证码发送失败，请重新获取");
	}

	 
	/**
	 * 扫码注册
	 * 跳转至注册页面
	 */
	public void regist() {
		String inviteUserid = getPara(0);
		logger.info("点击链接获取导购ID=======>"+inviteUserid);
	
		WxUser wxuser=getCurrentWxUser();		 
		if(wxuser==null){
			render("index.jsp");
			logger.error("微信用户为null");

		}else{
			//设置导购id到Session
			logger.info("导购ID保存到setSession=======>"+wxuser.getStr("daogouUid"));
			//设置导购id到Session
			if (wxuser.getStr("daogouUid")!=null &&  wxuser.getStr("daogouUid")!="") {
				setSessionAttr("inviteUserid", wxuser.getStr("daogouUid"));
			}else {
				logger.error("导购id为null或不是第一次扫码登陆");
			}
			render("regist.jsp");	
		}
		
	}


	/**
	 * 微信OAuth2网页授权回调处理
	 */
	@Clear
	public void oauth() {
		logger.info("oauth======>");
		String code = getPara("code");
		String validcode = getPara("state");
		String backurl = getPara("backurl");
		String session_validcode = getSessionAttr(Constants.WX_OAUTH_VALIDCODE);
		logger.error("code:" + code + ",state:" + validcode + ",backurl:" + backurl + ",session_validate:"
				+ session_validcode);
		if (StrKit.isBlank(validcode) || StrKit.isBlank(session_validcode) || !validcode.equals(session_validcode)) {
			logger.error("参数错误！");
			removeSessionAttr(Constants.WX_OAUTH);
			redirect("/index");
			return;
		}
		// 移除验证码
		removeSessionAttr(Constants.WX_OAUTH_VALIDCODE);
		if (StrKit.isBlank(code)) {
			// 用户未同意授权，此时可不理会，依然跳转首页
			logger.error("用户未同意授权，此时可不理会，依然跳转首页");
		} else {
			logger.error("用户同意授权，获取access_token");
			// 请求接口，获取access_token
			SnsAccessToken result = SnsAccessTokenApi.getSnsAccessToken(ApiConfigKit.getApiConfig().getAppId(),
					ApiConfigKit.getApiConfig().getAppSecret(), code);
			if (result.getErrorCode() != null) {
				// 获取access_token失败，此时可不理会，依然跳转首页
				logger.error("获取access_token异常：" + result.getErrorCode() + "，" + result.getErrorMsg());
			} else {
				logger.error("成功获取access_token，准备获取用户信息");
				// 成功，获取用户信息
				ApiResult userinfo = SnsApi.getUserInfo(result.getAccessToken(), result.getOpenid());
				logger.error("获取用户信息：" + userinfo.getJson());
				if (userinfo.isSucceed()) {
					logger.error("获取用户信息成功！");
					String openid = userinfo.getStr("openid");
					// 判断用户信息是否已经存在
					WxUser wxUser = WxUser.me().findFirst("SELECT * FROM t_bus_user_wx WHERE openid=?", openid);
					if (wxUser != null) {
						logger.error("微信用户已经存在，更新！");
						// 更新
						Db.update(
								"UPDATE t_bus_user_wx SET nickname=?,sex=?,province=?,city=?,country=?,headimgurl=?,unionid=?,access_token=?,refresh_token=? WHERE openid=?",
								userinfo.getStr("nickname").replaceAll("[\\ud800\\udc00-\\udbff\\udfff\\ud800-\\udfff]", "LF"), userinfo.getInt("sex"), userinfo.getStr("province"),
								userinfo.getStr("city"), userinfo.getStr("country"), userinfo.getStr("headimgurl"),
								userinfo.getStr("unionid"), result.getAccessToken(), result.getRefresh_token(),
								userinfo.getStr("openid"));
					} else {
						logger.error("微信用户不存在，添加！");
						// 添加
						//CommonKit.filterEmoji(userinfo.getStr("nickname"))不能过滤软键盘特殊符号
						Db.update(
								"INSERT INTO t_bus_user_wx(openid,nickname,sex,province,city,country,headimgurl,unionid,access_token,refresh_token) VALUES(?,?,?,?,?,?,?,?,?,?)",
								userinfo.getStr("openid"), userinfo.getStr("nickname").replaceAll("[\\ud800\\udc00-\\udbff\\udfff\\ud800-\\udfff]", "LF"), userinfo.getInt("sex"),
								userinfo.getStr("province"), userinfo.getStr("city"), userinfo.getStr("country"),
								userinfo.getStr("headimgurl"), userinfo.getStr("unionid"), result.getAccessToken(),
								result.getRefresh_token());
					}
					
					// 再获取最新的微信信息保存，以便用户进行注册或登录时，记录关联关系
					setSessionAttr(Constants.WX_USER,
							WxUser.me().findFirst("SELECT A.*,B.phone FROM t_bus_user_wx A left join t_bus_user B on A.userid=B.id WHERE A.openid=?", openid));
				} else {
					logger.error("获取用户信息失败！");
				}
			}
		}
		// 记录变量，表示已经进行过用户授权，不需要再进行第二次
		setSessionAttr(Constants.WX_OAUTH, true);
		if (StrKit.isBlank(backurl)) {
			logger.error("重定向至首页");
			// 重定向至首页
			redirect("/index");
		} else {
			logger.error("重定向至" + backurl);
			redirect(backurl);
		}
	}
}
